<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="../assets/js/vue.js"></script>
    <title>v-for</title>
</head>

<body>
    <h1>v-for 实例</h1>
    <hr>
    <div id="app">
        <ul>
            <li v-for="item in sortItems">
                {{item}}
            </li>
        </ul>
        <hr>
        <ul>
            <li v-for="(student,index) in sortstudents">{{index+1}}-{{student.name}} - {{student.age}}</li>
        </ul>
    </div>
    <script type="text/javascript">
        var app = new Vue({
            el: '#app',
            data: {
                items: [20, 23, 18, 7, 32, 19, 54, 56, 41],
                students: [
                    {name: "Link",age: 18},
                    {name: "Zelda",age: 20},
                    {name: "Lisa",age: 12},
                    {name: "Mipha",age: 19},
                ]
            },
            //渲染前排序--计算属性
            computed: {
                sortItems: function () {
                    return this.items.sort(sortNumber);
                },
                sortstudents: function () {
                    return sortByKey(this.students,"age");
                },
            }
        });
        //排序函数
        function sortNumber(a, b) {
            return a - b     //升序
            // return b - a  降序
        };
        //数组对象方法排序:
        function sortByKey(array, key) {
            return array.sort(function (a, b) {
                var x = a[key];
                var y = b[key];
                return ((x < y) ? -1 : ((x > y) ? 1 : 0));
            });
        }
    </script>
</body>

</html>